package platformlog_logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"yunzhan/common/models"

	"yunzhan/api-server/internal/svc"
	"yunzhan/api-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateHeartbeatsInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUpdateHeartbeatsInfoLogic 更新心跳信息
func NewUpdateHeartbeatsInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateHeartbeatsInfoLogic {
	return &UpdateHeartbeatsInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateHeartbeatsInfoLogic) UpdateHeartbeatsInfo(req *types.UpdateHeartbeatsRequest) (resp *types.UpdateHeartbeatsResponse, err error) {
	flag := l.svcCtx.Config.UseMysql

	var updateSQL string
	if flag {
		updateSQL = fmt.Sprintf(`
		UPDATE yunfan_bigdata.agent_heartbeats
		SET status = ?,
			host_name = ?,
			ip_address = ?
		WHERE agent_id = ? AND cluster_id = %s`, req.ClusterID)

	} else {
		updateSQL = fmt.Sprintf(`
		UPDATE agent_heartbeats
		SET status = ?,
			host_name = ?,
			ip_address = ?
		WHERE agent_id = ? AND cluster_id = %s`, req.ClusterID)

	}

	err = l.svcCtx.Conn.TransactCtx(context.Background(), func(ctx context.Context, sess sqlx.Session) error {
		_, err = sess.ExecCtx(ctx, updateSQL, req.Status, req.HostName, req.IPAddress, req.AgentId)
		if err != nil {
			logx.Errorf("failed to execute update: %v", err)
			return err
		}
		return nil
	})

	if err != nil {
		logx.Errorf("failed to update heartbeats info: %v", err)
		return nil, err
	}

	return &types.UpdateHeartbeatsResponse{
		Code:    200,
		Message: "心跳信息更新完成",
		Data: models.HeartbeatInfo{
			AgentId:   req.AgentId,
			HostName:  req.HostName,
			IPAddress: req.IPAddress,
			Status:    req.Status,
		},
	}, nil
}
